import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

import 'package:get_storage/get_storage.dart';
import 'package:nfc_manager/nfc_manager.dart';
import 'package:signage/app/data/models/devices_gruop_bean.dart';
import 'package:signage/app/modules/device/add_device/controllers/add_device_controller.dart';
import 'package:signage/app/modules/device/add_device/views/add_device_view.dart';
import 'package:signage/app/routes/app_pages.dart';
import 'package:signage/app/services/bluetooth_service.dart';
import 'package:signage/app/utils/sp_util.dart';
import 'package:signage/app/utils/toast_utils.dart';
import 'package:signage/l10n/l10n.dart';
import 'package:uuid/uuid.dart';

import '../models/device_cached_info.dart';

class DeviceController extends FullLifeCycleController
    with FullLifeCycleMixin, GetTickerProviderStateMixin {
  final BluetoothManager bluetoothManager = Get.find<BluetoothManager>();

  // ESL Service UUID (Electronic Shelf Label Service)
  static const String ESL_SERVICE_UUID = "1857"; // 16-bit UUID
  static const String DISPLAY_INFO_UUID = "2bfa"; // 16-bit UUID
  // 或完整的 128-bit UUID
  // static const String DISPLAY_INFO_UUID = "00002AA2-0000-1000-8000-00805F9B34FB";

  // 添加电池服务和特征的 UUID 常量
  static const String BATTERY_SERVICE_UUID = "180F";
  static const String BATTERY_LEVEL_UUID = "2A19";

  // 添加设备信息服务和特征的 UUID 常量
  static const String DEVICE_INFO_SERVICE_UUID = "180A";
  static const String FIRMWARE_VERSION_UUID = "2A26";

  // Add new map to track connection states
  final deviceConnectionStates = <String, bool>{}.obs;
  // Add method to check if any device is connecting
  final isConnectingDevice = false.obs;

  // Add new group-related properties
  final deviceGroups = <DevicesGroupBean>[].obs;
  final currentGroup = DevicesGroupBean(group: '', groupId: '').obs;

  final selectedDevices = <DeviceCachedInfo>[].obs;

  final isEdit = false.obs;

  late TabController tabController;
  @override
  void onInit() {
    super.onInit();
    tabController = TabController(length: 3, vsync: this);
    
    // Read and parse the saved groups
    final savedGroupsJson = SpUtil.getList('device_groups_2') ?? [];
    final savedGroups = savedGroupsJson.map((json) => 
      DevicesGroupBean.fromJson(json as Map<String, dynamic>)
    ).toList();
    
    if (savedGroups.isEmpty) {
      savedGroups.add(DevicesGroupBean(
        group: AppLocalizations.of(Get.context!)!.translate('device_default_group'),
        groupId: '0'
      ));
    }
    
    deviceGroups.value = savedGroups;
    currentGroup.value = savedGroups.first;
  }

  @override
  void onReady() {
    super.onReady();
    print('🚀 Controller is ready');
  }

  @override
  void onDetached() {
    print('🔌 App detached');
  }

  @override
  void onInactive() {
    print('💤 App inactive');
  }

  @override
  void onPaused() {
    print('⏸️ App paused');
  }

  @override
  void onResumed() {
    print('📱 App resumed - attempting to connect to cached devices');
  }

  @override
  void onClose() {
    // 断开所有设备连接
    super.onClose();
  }

  @override
  void onHidden() {
    print('🙈 App hidden');
  }

  Future<void> addDevice(List<String> deviceIds,
      {String? group, String? type, String? from, String? groupId}) async {
    try {
      print('🔄 [addDevice] Starting device addition process');
      print('📱 [addDevice] Device IDs: ${deviceIds.join(", ")}');
      print('📍 [addDevice] Group: $group, Type: $type, From: $from');

      EasyLoading.show(
          status: AppLocalizations.of(Get.context!)!.translate('device_connecting'));

      if (FlutterBluePlus.isScanningNow) {
        print('⏸ [addDevice] Stopping existing scan');
        await bluetoothManager.stopScan();
        await FlutterBluePlus.isScanning.where((val) => val == false).first;
      }

      List<BluetoothDevice> devices = [];

      if (type == 'nfc') {
        print('🔍 [addDevice] Processing NFC device');
        final nfcDeviceId = bluetoothManager.nfcScanResults.first.id;
        print('📱 [addDevice] Scanning for NFC device: $nfcDeviceId');
        
        final device = await bluetoothManager.scanForDevice(nfcDeviceId);
        if (device != null) {
          print('✅ [addDevice] NFC device found and added to list');
          devices = [device];
        } else {
          print('⚠️ [addDevice] NFC device not found during scan');
        }
      } else {
        print('🔍 [addDevice] Processing Bluetooth devices');
        devices = bluetoothManager.scanResults
            .where((element) => deviceIds.contains(element.device.remoteId.toString()))
            .map((element) => element.device)
            .toList();
        print('📱 [addDevice] Found ${devices.length} matching devices');
      }

      print('🔄 [addDevice] Starting batch connection process');
      await bluetoothManager.processBatchConnections(devices);

      if (type == 'nfc') {
        print('📝 [addDevice] Updating NFC device info in cache');
        bluetoothManager.nfcScanResults.forEach((element) {
          bluetoothManager.deviceInfoMap[element.id] = element.copyWith(
            lastConnected: DateTime.now(),
            group: group ?? currentGroup.value.group,
            groupId: groupId ?? currentGroup.value.groupId,
            canCast: true,
          );
        });
      } else {
        print('📝 [addDevice] Updating Bluetooth devices info in cache');
        for (var deviceId in deviceIds) {
          final deviceInfoResult = bluetoothManager.connectedDevices
              .firstWhere((d) => d.id == deviceId);
          
          if(deviceInfoResult.displayInfo.isNotEmpty) {
            print('✅ [addDevice] Adding device $deviceId to cache');
            bluetoothManager.deviceInfoMap[deviceId] = deviceInfoResult.copyWith(
              lastConnected: DateTime.now(),
              group: group ?? currentGroup.value.group,
              groupId: groupId ?? currentGroup.value.groupId,
              canCast: true,
            );
          } else {
            print('⚠️ [addDevice] Device $deviceId has no display info');
          }
        }
      }

      print('💾 [addDevice] Saving devices to storage');
      await bluetoothManager.saveDevicesToStorage();
      
      ToastUtils.showSuccess(
          AppLocalizations.of(Get.context!)!.translate('device_bind_success'));
      
      print('✅ [addDevice] Device addition completed successfully');
    } catch (e) {
      print('❌ [addDevice] Error adding device: $e');
      rethrow;
    } finally {
      EasyLoading.dismiss();
    }
  }

  // 获取设备连接状态
  Stream<BluetoothConnectionState> getDeviceConnectionState(String deviceId) {
    try {
      final device = FlutterBluePlus.connectedDevices
          .firstWhere((d) => d.remoteId.toString() == deviceId);
      return device.connectionState;
    } catch (e) {
      // 如果设备未连接，返回一个带有断开状态的Stream
      return Stream.value(BluetoothConnectionState.disconnected);
    }
  }

  // 获取设备缓存信息的方法
  DeviceCachedInfo? getDeviceCachedInfo(String deviceId) {
    final cachedInfo = bluetoothManager.deviceInfoMap[deviceId];
    return cachedInfo;
  }

  // Add method to add new group
  void addGroup(String groupName) {
    if (!deviceGroups.contains(groupName)) {
      deviceGroups
          .add(DevicesGroupBean(group: groupName, groupId: Uuid().v4()));
      _saveGroupsToStorage();
    }
  }

  // Add method to change current group
  void changeGroup(DevicesGroupBean group) {
    currentGroup.value = group;
  }

  // Add method to assign device to group
  void assignDeviceToGroup(String deviceId, String groupName) {
    if (bluetoothManager.deviceInfoMap.containsKey(deviceId)) {
      final deviceInfo = bluetoothManager.deviceInfoMap[deviceId]!;
      bluetoothManager.deviceInfoMap[deviceId] =
          deviceInfo.copyWith(group: groupName);
      bluetoothManager.saveDevicesToStorage();
    }
  }

  // Add method to save groups
  void _saveGroupsToStorage() {
    try {
      // Convert groups to JSON before saving
      final groupsJson = deviceGroups.map((group) => group.toJson()).toList();
      SpUtil.setList('device_groups_2', groupsJson);
    } catch (e) {
      printError(info: 'Error saving groups: $e');
    }
  }

  void scanDevice(BuildContext context) {
    Get.bottomSheet(
      GetBuilder<AddDeviceController>(
        init: AddDeviceController(),
        initState: (_) {},
        builder: (AddDeviceController controller) {
          return Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(18.r),
                  topRight: Radius.circular(18.r)),
            ),
            height: Get.height * 0.85,
            child: AddDeviceView(),
          );
        },
      ),
      enterBottomSheetDuration: 300.milliseconds,
      exitBottomSheetDuration: 300.milliseconds,
      backgroundColor: Colors.white,
      elevation: 1,
      settings: RouteSettings(name: Routes.ADD_DEVICE, arguments: {
        'group': currentGroup.value.group,
        'groupId': currentGroup.value.groupId,
        'type': 'bluetooth'
      }),
      ignoreSafeArea: false,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.r), topRight: Radius.circular(20.r))),
    );
  }

  void selectDevice(DeviceCachedInfo deviceCachedInfo) {
    if (isEdit.value) {
      print('selectDevice: ${deviceCachedInfo.id}');
      if (selectedDevices.any((d) => d.id == deviceCachedInfo.id)) {
        selectedDevices.remove(deviceCachedInfo);
      } else {
        selectedDevices.add(deviceCachedInfo);
      }
    }
  }

  void moveDevices() {
    if (selectedDevices.isEmpty) {
      ToastUtils.showError(
          AppLocalizations.of(Get.context!)!.translate('device_please_select'));
      return;
    }

    if (deviceGroups.length == 1) {
      ToastUtils.showError(AppLocalizations.of(Get.context!)!
          .translate('device_please_add_group'));
      return;
    }

    Get.bottomSheet(
      Material(
        color: Colors.transparent,
        child: Container(
          width: Get.width,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.only(
                topLeft: Radius.circular(18.r),
                topRight: Radius.circular(18.r)),
          ),
          child: Column(
            children: [
              Container(
                  height: 68.h,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(247, 247, 247, 1),
                    borderRadius: BorderRadius.only(
                        topLeft: Radius.circular(18.r),
                        topRight: Radius.circular(18.r)),
                  ),
                  child: Center(
                    child: Text(
                      AppLocalizations.of(Get.context!)!
                          .translate('device_move_to'),
                      style: TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.w400,
                        letterSpacing: 0,
                        color: Color.fromRGBO(51, 51, 51, 1),
                      ),
                    ),
                  )),
              Expanded(
                child: ListView.builder(
                  itemCount: deviceGroups.length,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      behavior: HitTestBehavior.translucent,
                      onTap: () {
                        selectedDevices.forEach((device) {
                          bluetoothManager.deviceInfoMap[device.id] =
                              device.copyWith(
                            lastConnected: DateTime.now(),
                            group: deviceGroups[index].group,
                            groupId: deviceGroups[index].groupId,
                            canCast: true,
                          );
                        });
                        changeGroup(deviceGroups[index]);
                        Get.back();
                      },
                      child: Container(
                        height: 40.h,
                        padding: EdgeInsets.symmetric(horizontal: 24.w),
                        child: Row(
                          // 设置宽度为拉满
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text(
                                deviceGroups[index].groupId == '0'
                                    ? AppLocalizations.of(Get.context!)!
                                        .translate('device_default_group')
                                    : deviceGroups[index].group,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Color(0XFF333333),
                                )),
                            if (deviceGroups[index].groupId ==
                                currentGroup.value.groupId)
                              Image.asset(
                                  'assets/images/Group 1321318579@2x.png',
                                  width: 22.w,
                                  height: 22.h),
                          ],
                        ),
                      ),
                    );
                  },
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  void startScreen() {
    if (selectedDevices.isEmpty) {
      ToastUtils.showError(
          AppLocalizations.of(Get.context!)!.translate('device_please_select'));
      return;
    }
  }

  void clearScreen() {
    if (selectedDevices.isEmpty) {
      ToastUtils.showError(
          AppLocalizations.of(Get.context!)!.translate('device_please_select'));
      return;
    }

    Get.toNamed(Routes.CAST_PROGRESS, arguments: {
      'devices': selectedDevices,
      'isClear': true,
    });
  }

  selectDeviceByNfc() async {
    bool isAvailable = await NfcManager.instance.isAvailable();
    if (!isAvailable) {
      ToastUtils.showError(AppLocalizations.of(Get.context!)!
          .translate('device_nfc_not_available'));
      return;
    }
    Get.bottomSheet(
      GetBuilder<AddDeviceController>(
        init: AddDeviceController(),
        initState: (_) {},
        builder: (AddDeviceController controller) {
          return Container(
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(18.r),
                  topRight: Radius.circular(18.r)),
            ),
            height: Get.height * 0.85,
            child: AddDeviceView(),
          );
        },
      ),
      enterBottomSheetDuration: 300.milliseconds,
      exitBottomSheetDuration: 300.milliseconds,
      backgroundColor: Colors.white,
      elevation: 1,
      settings: RouteSettings(name: Routes.ADD_DEVICE, arguments: {
        'group': currentGroup.value.group,
        'groupId': currentGroup.value.groupId,
        'type': 'nfc'
      }),
      ignoreSafeArea: false,
      isScrollControlled: true,
      shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20.r), topRight: Radius.circular(20.r))),
    );
  }
}
